package com.exahq.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.exahq.common.lang.Result;
import com.exahq.entity.Admin;
import com.exahq.service.AdminService;
import com.exahq.util.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lhq
 * @since 2021-01-25
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService adminService;



    @RequiresAuthentication
    @PostMapping("/edit")
    public Result edit(@Validated @RequestBody Admin admin) {
        Admin temp = null;
        if(admin.getId() != null) {
            temp = adminService.getById(admin.getId());
            Assert.isTrue(temp.getId() == ShiroUtil.getProfileAdmin().getId(), "没有权限编辑");
        } else {
            temp = new Admin();
            temp.setDelFlag("1");
            temp.setAStatus(0);
            temp.setAPassword(SecureUtil.md5(admin.getAPassword()));
            temp.setAName(admin.getAName());
        }

        BeanUtil.copyProperties(admin, temp, "id", "aName", "aPassword", "state","del_flag","aStatus");

        adminService.saveOrUpdate(temp);
        return Result.succ("操作成功", null);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Admin admin = adminService.getById(id);
        return Result.succ(admin);
    }

    @RequiresAuthentication
    @GetMapping("del/{id}")
    public Result del(@PathVariable(name = "id") Long id) {
        Admin admin = adminService.getById(id);
        admin.setDelFlag("0");
        adminService.saveOrUpdate(admin);
        Assert.notNull(admin, "该管理员已删除！");
        return Result.succ(admin);
    }
}
